/*
 * Copyright 2020-2030 ALPHA LAB.Inc All Rights Reserved.
 */
package com.alphalab.framework.log;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import org.apache.log4j.MDC;

/**
 * 拓展log4j显示ip、用户名等上下文信息.
 * @author allen
 * @version 1.0.0 2020年2月24日
 */
@WebFilter(filterName = "Log4jFilter",urlPatterns = {"/*"})
public class Log4jFilter implements Filter {
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String ip = request.getRemoteAddr();
		//通过session获取用户名
//		String userName = (String)((HttpServletRequest)request).getSession().getAttribute("userName");
		MDC.put("ip", ip);
		MDC.put("userName", "Bryant");
		chain.doFilter(request, response);
		MDC.remove("ip");
		MDC.remove("userName");
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	
	@Override
	public void destroy() {
	}

}
